<template>
  <div class="sign-form-item">
    <div class="title"><div class="dot"/>基础信息</div>
    <el-form
      ref="formRef"
      :model="modelData"
      :rules="formRules"
      :label-width="labelWidth"
      class="lineHeight32"
      label-position="right">
      <el-row type="flex" class="response-el-row">
        <el-col :span="rowSpan">
          <el-form-item prop="orderPlatformId" label="平台">
            <selectWithoutHttp
              v-model="platformObj"
              :list-data="orderPlatformOption"
              class="width240"
              key-name="id"
              label-name="value"
              value-type="object"
              @change="platformChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item prop="accountName" label="账号">
            <div class="flex-center">
              <el-input v-model="modelData.accountName" :maxlength="50" class="width240" placeholder="请输入账号" type="text" size="small" />
              <span v-if="accountResult" :class="`label-bg${accountResult.result}`" class="account-label">{{ accountResult.result | formatResult }}</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item prop="link" label="主页链接">
            <el-input v-model="modelData.link" :disabled="isWeixin" :maxlength="500" clearable class="width240" placeholder="请输入主页链接" type="text" size="small" />
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item prop="accountCode" label="账号ID">
            <el-input v-model="modelData.accountCode" :maxlength="50" class="width240" placeholder="请输入账号ID" type="text" size="small" @change="getAccountStatus"/>
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item label="达人所在城市" prop="area">
            <three-level-area
              :selected-options="formatArea(modelData.area)"
              class="height32"
              clearable
              separator="-"
              select-type="city"
              placeholder="省-市"
              @update:options="threeLevelArea($event)" />
          </el-form-item>
        </el-col>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="modelData.gender">
            <el-radio :label="0"><span class="radio-label">男</span></el-radio>
            <el-radio :label="1"><span class="radio-label">女</span></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-col :span="rowSpan">
          <el-form-item label="标签" prop="tagName" style="margin-bottom: 0">
            <template slot="label">
              <span style="display: inline-flex;align-items: center;">标签
                <InfoIcon content="标签最多可选择3个" style="width: 16px;height: 16px;margin-left: 4px;" />
              </span>
            </template>
            <TagSelect v-model="modelData.tagName" :module-type="TAG_MODULES.SIGN_UP" :platform="platformObj.id" need-plat-form-params limit class="tag-select" />
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item label="是否挂靠" prop="microtask">
            <selectWithoutHttp v-model="modelData.microtask" :list-data="dependOptions" class="width240" key-name="id" label-name="value"/>
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item label="粉丝量" prop="fansNum">
            <el-input
              v-model="modelData.fansNum"
              :maxlength="9"
              class="width240"
              placeholder="请输入粉丝量"
              oninput="if(value>999999999)value=999999999;if(value<0)value=0;"
              name="fansNum"
              size="small"
              @mousewheel.native.prevent
              @input="numInputChange($event, 'fansNum')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item label="点赞数" prop="likeNum">
            <el-input
              v-model="modelData.likeNum"
              :maxlength="9"
              class="width240"
              placeholder="请输入点赞数"
              oninput="if(value>999999999)value=999999999;if(value<0)value=0;"
              name="likeNum"
              size="small"
              @mousewheel.native.prevent
              @input="numInputChange($event, 'likeNum')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item label="评论数" prop="commentNum">
            <el-input
              v-model="modelData.commentNum"
              :maxlength="9"
              class="width240"
              placeholder="请输入评论数"
              oninput="if(value>999999999)value=999999999;if(value<0)value=0;"
              name="commentNum"
              size="small"
              @mousewheel.native.prevent
              @input="numInputChange($event, 'commentNum')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item label="收藏数" prop="favouritesNum">
            <el-input
              v-model="modelData.favouritesNum"
              :maxlength="9"
              class="width240"
              placeholder="请输入收藏数"
              oninput="if(value>999999999)value=999999999;if(value<0)value=0;"
              name="favouritesNum"
              size="small"
              @mousewheel.native.prevent
              @input="numInputChange($event, 'favouritesNum')"
            />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="rowSpan">
          <el-form-item label="报备价格(元)" prop="quotationPrice">
            <el-input
              v-model="modelData.quotationPrice"
              :maxlength="12"
              class="width240"
              placeholder="请输入报备价格"
              oninput="if(value>999999999)value=999999999;if(value<0)value=0;"
              name="quotationPrice"
              size="small"
              @mousewheel.native.prevent
              @input="numInputChange($event, 'quotationPrice')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item label="非报备价格(元)" prop="notReportPrice">
            <el-input
              v-model="modelData.notReportPrice"
              :maxlength="12"
              class="width240"
              placeholder="请输入非报备价格"
              oninput="if(value>999999999)value=999999999;if(value<0)value=0;"
              name="notReportPrice"
              size="small"
              @mousewheel.native.prevent
              @input="numInputChange($event, 'notReportPrice')"
            />
          </el-form-item>
        </el-col> -->
        <!-- 动态字段 -->
        <el-col v-for="(item) in modelData.dynamicKey" :key="item.name" :span="rowSpan">
          <el-form-item :prop="item.name">
            <el-tooltip slot="label" :content="item.name" placement="top" effect="dark">
              <div class="item ellipsisOne">
                {{ item.name }}
              </div>
            </el-tooltip>
            <dynamicKey :item="item" />
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan">
          <el-form-item label="接单偏好" prop="preference">
            <el-input v-model="modelData.preference" :maxlength="1000" resize="none" class="width240" placeholder="请描述该账号接单偏好" type="textarea" size="small" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import ThreeLevelArea from '@/components/ThreeLevelArea';
import TagSelect from '@/components/Common/tagSelect';
import { platformList } from '@/api/select';
import { getOperateoptions } from '@/api/resource';
import { getFilterList } from '@/api/filter';
import dynamicKey from './dynamicKey';
import { TAG_MODULES } from '@/utils/const';
import { formatResult } from '@/filters/status';

export default {
  filters: { formatResult },
  components: { selectWithUserLoad, selectWithoutHttp, dynamicKey, ThreeLevelArea, TagSelect },
  model: {
    prop: 'modelData',
    event: 'changeValue'
  },
  props: {
    modelData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    labelWidth: {
      type: String,
      default: '110px'
    },
    isCreateSupplier: {
      type: Boolean,
      default: false
    },
    formFlyUser: {// 是否从飞来用户发起
      type: Boolean,
      default: false
    },
    rowSpan: {
      type: Number,
      default: 12
    }
  },
  data() {
    return {
      TAG_MODULES,
      dependOptions: [{ value: '是', id: 1 }, { value: '否', id: 0 }],
      isSignOptions: [{ value: '未签约', id: 0 }, { value: '已签约', id: 1 }, { value: '已解约', id: -1 }],
      orderPlatformOption: [],
      defaultResourceOption: [],
      operateModeList: [], // 运营模式
      accountResult: ''
    };
  },
  computed: {
    formRules() {
      const requiredModel = this.modelData.requiredModel || {};
      const isWeixinPlatform = this.isWeixinPlatform;
      const obj = {
        orderPlatformId: [{ required: true, trigger: 'change', message: '请选择下单平台' }],
        accountName: [{ required: true, trigger: 'change', message: '请输入账号' }],
        link: [{ required: !(isWeixinPlatform || this.isWeixin), trigger: 'change', message: '请输入链接' }],
        accountCode: [{ required: true, trigger: 'change', message: '请输入账号ID' }],
        area: [{ required: true, trigger: ['change', 'blur'], message: '请选择达人所在城市' }],
        gender: [{ required: true, trigger: 'change', message: '请选择性别' }],
        tagName: [{ required: true, message: '请选择标签', trigger: 'change' }],
        operatingModelId: [{ required: true, trigger: 'change', message: '请选择运营模式' }],
        tagIds: [{ required: true, trigger: 'change', message: '请选择标签' }],
        microtask: [{ required: true, trigger: 'change', message: '请选择是否挂靠' }],
        // tagName: [{ required: true, trigger: 'blur', message: '请选择标签' }],
        fansNum: [{ required: true, trigger: 'blur', message: '请输入粉丝量' }],
        ...requiredModel
      };
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
      return obj;
    },
    isWeixin() {
      const orderPlatformId = this.modelData.orderPlatformId;
      const orderPlatformOption = this.orderPlatformOption;
      if (!orderPlatformOption && orderPlatformOption.length === 0) return false;
      const platform = orderPlatformOption.find(i => i.id === orderPlatformId);
      if (platform) {
        return platform.value === '微信视频号';
      }
      return false;
    },
    isWeixinPlatform() {
      const orderPlatformId = this.modelData.orderPlatformId;
      const orderPlatformOption = this.orderPlatformOption;
      if (!orderPlatformOption && orderPlatformOption.length === 0) return false;
      const platform = orderPlatformOption.find(i => i.id === orderPlatformId);
      if (platform) {
        return platform.value === '微信';
      }
      return false;
    },
    platformObj: {
      get() {
        return {
          id: this.modelData.orderPlatformId,
          value: this.modelData.platformName
        };
      },
      set(data) {
        this.modelData.platformName = data.value;
        this.modelData.orderPlatformId = data.id;
      }
    }

  },
  watch: {
    'modelData.orderPlatformId': {
      handler(newVal, oldVal) {
        if (newVal && !oldVal && this.formFlyUser) { // 飞来用户回填获取自定义字段
          this.platformChange({ id: newVal });
        }
        this.getAccountStatus();
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.platformList();
    this.getOperate();
  },
  methods: {
    async getAccountStatus() {
      if (this.platformObj && this.platformObj.id && this.modelData.accountCode) {
        const params = {
          platformIds: this.platformObj.id,
          accountId: this.modelData.accountCode,
          page: 1,
          perPage: 100,
          accurateSearch: 1
        };
        const res = await getFilterList(params);
        if (res.code === 200 && res.data && res.data.items) {
          this.accountResult = res.data.items[0];
        }
      } else {
        return new Promise((resolve, reject) => {
          reject();
        });
      }
    },
    platformChange(data) {
      this.$emit('platformChange', data.id);
      if (this.isWeixin) {
        this.$set(this.modelData, 'link', '');
      }
      this.modelData.tagName = [];
      // this.$nextTick(() => {
      //   this.$refs.formRef.clearValidate();
      // });
    },
    // 获取下单平台的列表
    async platformList() {
      try {
        const result = await platformList();
        this.orderPlatformOption = result.data;
      } catch (error) {
        console.log(error);
      }
    },
    // 获取运营模式的列表
    getOperate() {
      getOperateoptions().then(res => {
        this.operateModeList = res.data;
      });
    },
    validateForm(validate = true) {
      return new Promise((resolve, reject) => {
        if (validate) {
          this.$refs.formRef.validate(valid => {
            if (valid) {
              resolve(valid);
            } else {
              reject();
            }
          });
        } else {
          resolve(true);
        }
      });
    },
    // 选择城市
    threeLevelArea(data) {
      this.$set(this.modelData, 'area', data.join('-'));
    },
    formatArea(data) {
      if (!data) return [];
      if (typeof data === 'string') {
        return data.indexOf('-') > -1 ? data.split('-') : data.split(',');
      } else {
        return data;
      }
    },
    numInputChange(text, prop) {
      let str;
      str = text.replace(/[^\d.]/g, '');
      if (['quotationPrice', 'notReportPrice'].includes(prop)) {
        str = str.replace(/\.{2,}/g, '.'); // 连续两个小数点 replace为.
        str = str.replace(/^\./g, '0.'); // 已点为开头 replace为 0.
        str = str.replace(/^(\d*)\.(\d*)\./g, '$1.$2');// 不连续点点 删掉
        str = str.replace(/^0[^\.]+/g, '0'); // 连续多个0 replace为1个0
        str = str.replace(/^(\-?\d+)\.(\d\d).*$/, '$1.$2'); // 只允许保留小数点后2位
      } else if (str !== '0') {
        str = str.replace(/\.|^0/g, ''); // 数量只允许输入正整数
      }
      this.modelData[prop] = str || null;
      this.$forceUpdate();
    }
  }
};
</script>

<style lang="scss" scoped>
.sign-form-item {
  &::v-deep {
    .el-form-item__label {
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
    .el-form-item__error {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 240px;
    }
    .el-cascader {
      line-height: 0;
    }
  }
  .radio-label {
    font-size: 14px;
    color: #333;
  }
}
.width240 {
  width: 240px;
  &::v-deep {
    .el-select {
      width: 240px;
    }
    .el-input__inner {
      width: 240px;
      height: 32px;
    }
    .el-tag.el-tag--info {
      color: #406eff !important;
      background: #eff3fb;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
}
.title {
  font-size: 16px;
  font-weight: 600;
  text-align: left;
  color: #333333;
  line-height: 16px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  .dot {
    width: 4px;
    height: 4px;
    background-color: #406EFF;
    margin-right: 6px;
  }
}
.field-shrink-spacing {
  &::v-deep {
    .el-form-item__label {
      overflow: hidden;
      -webkit-line-clamp: 2;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      text-overflow: ellipsis;
      line-height: 1.2 !important;
    }
  }
}
.account-label {
  height: 20px;
  margin-left: 6px;
  padding: 2px 8px;
  font-size: 12px;
  line-height: 16px;
  font-weight: 500;
  border-radius: 10px;
  color: #fff;
}
.label-bg0 {
  background: #406eff;
}
.label-bg1 {
  background: #FD8546;
}
.label-bg2 {
  background: #31CC9C;
}
.label-bg3 {
  background: #FF4E5F;
}
.tag-select {
  width: 240px;
  ::v-deep {
    .el-cascader {
      width: 100%;
    }
  }
}
</style>
